
package com.anzym.android.kegdroidkey;

import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources.NotFoundException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.anzym.android.kegdroidlibrary.models.KegDroid;
import com.anzym.android.kegdroidlibrary.tasks.FetchBeerTask;
import com.anzym.android.kegdroidkey.tasks.FetchKegDroidTask;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

public class KegDroidKeyActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {

    private static final String TAG = KegDroidKeyActivity.class.getSimpleName();
    public static SharedPreferences settings = null;
    private static final int REQUEST_CODE_EXIT_APP = 8000;
    private static final int SIGNED_IN = 8001;
    private static final int LOGGED_OUT = 8002;
    private boolean IS_LOGGED_IN = false;
    KegDroidKeyApplication keyApp;
    private TextView userGplusId;
    private ImageView userImageView;
    private Context ctx;
    private NfcAdapter mAdapter;
    
    private BeamDialog bd;

    ListView kdListView;
    ArrayList<KegDroid> kdList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        kdList = new ArrayList<KegDroid>();
        setContentView(R.layout.kegdroid_list);
        ctx = this;
       
        keyApp = KegDroidKeyApplication.getInstance();
        settings = keyApp.getSettings();
        keyApp.getUser().setEmailAddress(settings.getString("email_address",
                getResources().getString(R.string.default_email)));
        keyApp.getUser().setGPlusId(settings.getString("gplus_id", getResources()
                .getString(R.string.default_id)));
        keyApp.getUser().setImageUrl(settings.getString("image_url", null));
        if (!keyApp.getUser().getEmailAddress()
                .equals(getResources().getString(R.string.default_email))) {
            Log.d(TAG, "not DEFAULT EMAIL ADDRESS");
            IS_LOGGED_IN = true;
        }
        if (!IS_LOGGED_IN) {
            Log.d(TAG, "NOT LOGGED IN");
            goLogin();
        }
        
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mAdapter.setNdefPushMessageCallback(this, this);
        mAdapter.setOnNdefPushCompleteCallback(this, this);
    }

    public void goLogin() {

        Intent userUpdateIntent = new Intent(KegDroidKeyActivity.this,
                DrinkerLoginActivity.class);
        KegDroidKeyActivity.this.startActivityForResult(userUpdateIntent, 0);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_keg_droid_key_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.login:
                goLogin();
                return true;
            case R.id.update_beers:
                updateBeerDatabase();
                return true;
            case R.id.refresh_kegdroids:
                updateKegDroidList();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume");
        // setupDisplay();
        refreshDisplay();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
        updatePrefs();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
        updatePrefs();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {
        if (resultCode == REQUEST_CODE_EXIT_APP) {
            Log.d(TAG, "EXITING LOGIN _ Exit APP");
            this.finish();
        } else if (resultCode == SIGNED_IN) {
            Log.d(TAG, "EXITING LOGIN _  SIGNED IN");
            IS_LOGGED_IN = true;
            updateKegDroidList();
        } else if (resultCode == LOGGED_OUT) {
            updatePrefs();
            this.finish();
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    void updatePrefs() {
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("email_address", keyApp.getUser().getEmailAddress());
        editor.putString("gplus_id", keyApp.getUser().getGPlusId());
        editor.putString("image_url", keyApp.getUser().getImageUrl());
        editor.commit();
    }

    public void refreshDisplay() {
        userGplusId = (TextView) findViewById(R.id.user_gplus_id);
        userGplusId.setText(keyApp.getUser().getGPlusId());
        kdListView = (ListView) findViewById(R.id.kegdroid_list_container);
        if (kdList.isEmpty() && IS_LOGGED_IN) {
            Log.d(TAG, "KEGDROID LIST IS EMPTY");
            Log.d(TAG, "kdList " + kdList);
            updateKegDroidList();
        } else {
            kdListView.setAdapter(new KegDroidListAdapter(this, kdList));
            kdListView.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> a, View v,
                        int position, long id) {

                    Object o = kdListView.getItemAtPosition(position);
                    KegDroid k = (KegDroid) o;

                    BeerOrderDialog bod = new BeerOrderDialog(ctx, k);
                    if (!bod.isShowing()) {
                        bod.show();
                    }
                }
            });
        }
    }

    public void updateKegDroidList() {
        Log.d(TAG, "updateKegDroidList");
        FetchKegDroidTask fetchKDTask = new FetchKegDroidTask(this, kdList);
        try {
            this.kdList = fetchKDTask.execute(keyApp.getUser().getGPlusId()).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        refreshDisplay();
    }

    public void updateBeerDatabase() {
        FetchBeerTask fetchBeer = new FetchBeerTask(this);
        fetchBeer.execute();
    }
    
    public void beamToKegDroid() {
        bd = new BeamDialog(ctx);
        bd.show();
    }

    
    @Override
    public NdefMessage createNdefMessage(NfcEvent event) {
        Log.d(TAG, "Creating NDEF MESSAGE");
        Log.d(TAG, "Name: " + keyApp.getUser().getGivenName());
        Log.d(TAG, "GPlusId: " + keyApp.getUser().getGPlusId());
        Log.d(TAG, "AndroidId " + keyApp.getBeerOrder().getAndroidId());
        Log.d(TAG, "TapNumber " + keyApp.getBeerOrder().getTapNumber());
        Log.d(TAG, "BeerId " + keyApp.getBeerOrder().getBeerId());
        Log.d(TAG, "OrderSize: " + keyApp.getBeerOrder().getOrderSize());
        Log.d(TAG, "ImageUrl: " + keyApp.getUser().getImageUrl());

        NdefMessage msg = null;
        try {
            msg = new NdefMessage(
                    new NdefRecord[] {
                            // NdefRecord.createExternal(getResources().getString(R.string.domain),
                            // "kegdroid_email",
                            // keyApp.getUser().getEmailAddress().getBytes("UTF-8"))
                            
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_name",
                                    keyApp.getUser().getGivenName().getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_gplusid",
                                    keyApp.getUser().getGPlusId().getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_android_id",
                                    keyApp.getBeerOrder().getAndroidId().getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_tapNumber",
                                    new Integer(keyApp.getBeerOrder().getTapNumber()).toString().getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_beer_id", new Long(keyApp.getBeerOrder().getBeerId()).toString()
                                            .getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_volume", new Integer(keyApp.getBeerOrder().getOrderSize())
                                            .toString().getBytes("UTF-8"))
                            ,
                            NdefRecord.createExternal(
                                    keyApp.getResources().getString(R.string.domain),
                                    "kegdroid_image_url",
                                    keyApp.getUser().getImageUrl().getBytes("UTF-8"))
                    });
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return msg;

    }

    @Override
    public void onNdefPushComplete(NfcEvent event) {
        if (bd.isShowing()) {
            bd.dismiss();
        }
    }

}
